package com.efounder.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.activity.Order.OrderGoodAdapter;
import com.efounder.adapter.BaseAdapter;
import com.efounder.adapter.OrderAdapter;
import com.efounder.adapter.OrderDetailPreAdapter;
import com.efounder.bean.*;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.ChatTextView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.holder.CreateOrderHolder;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.DialogUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.efounder.fragment.MallOrderFragment.ORDER_TYPE_NEW_VIRTUAL;
import static com.efounder.fragment.MallOrderFragment.ORDER_TYPE_TREASURE;
import static com.efounder.fragment.MallOrderFragment.ORDER_TYPE_VIRTUAL;
import static com.efounder.utils.MallRequestUtil.CART_ADD_OR_DELETE_URL;
import static com.efounder.utils.MallRequestUtil.ORDER_DETAIL_URL;

/**
 * 订单详情类
 * Created by will on 18-2-9.
 */

public class MallOrderDetailActivity extends BaseActivity implements View.OnClickListener {

    private String TAG = this.getClass().getSimpleName();

    private TextView tvCancleOrder;
    private TextView tvRebuy;
    private TextView tvNowPay;
    private TextView tvTreasureDetails;
    private TextView tvConfirmOrder;
    private TextView tvDeleteOrder;
    private TextView tv_order_immediate_evaluation;
    private String orderBh;
    private OrderDetail orderDetail;
    private RecyclerView order_rlv_pre_detail;
    private OrderDetailPreAdapter mAdapter;
    private ArrayList<OrderDetail.OrderBean.OrderSaleInfoListBean> mlist;
    private GoodsBean.TokenPricesBean tokenPricesBean;
    private ArrayList<GoodsBean> mGoodslist;
    private OrderGoodAdapter goodsAdapter;
    private LinearLayout rlBottomOrderStatus;
    private RelativeLayout rl_address;
    /**
     * 商家留言布局
     */
    private LinearLayout ll_business_message;
    private ChatTextView tv_business_message;

    /**
     * 交易哈希值
     *
     */
    private LinearLayout ll_deal_hash;
    private TextView tv_deal_hash_value;

    private int orderType = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent().getExtras() != null) {
            orderBh = getIntent().getExtras().getString("orderBh");
        }
        setContentView(R.layout.layout_order_detail);
        initRecycleView();
        initData();
    }

    private void initRecycleView() {
        order_rlv_pre_detail = (RecyclerView) findViewById(R.id.order_rlv_pre_detail);
        order_rlv_pre_detail.setLayoutManager(new LinearLayoutManager(this));
        rlBottomOrderStatus = (LinearLayout) findViewById(R.id.rl_bottom_order_status);
        rl_address = (RelativeLayout) findViewById(R.id.rl_address);
        ll_business_message = (LinearLayout) findViewById(R.id.ll_business_message);
        tv_business_message = (ChatTextView) findViewById(R.id.tv_business_message);
        ll_deal_hash = (LinearLayout) findViewById(R.id.ll_deal_hash);
        tv_deal_hash_value = (TextView) findViewById(R.id.tv_deal_hash_value);
        mlist = new ArrayList<>();
        mAdapter = new OrderDetailPreAdapter(mlist);
        order_rlv_pre_detail.setAdapter(mAdapter);
        RecyclerView order_detail_rlv = (RecyclerView) findViewById(R.id.order_detail_rlv);
        order_detail_rlv.setLayoutManager(new LinearLayoutManager(this));
        mGoodslist = new ArrayList<>();
        goodsAdapter = new OrderGoodAdapter(mGoodslist);
        order_detail_rlv.setAdapter(goodsAdapter);
        goodsAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<CreateOrderHolder>() {
            @Override
            public void onItemClick(CreateOrderHolder createOrderHolder, int pos) {
                Intent intent = new Intent(MallOrderDetailActivity.this, ProductDetailsActivity.class);
                intent.putExtra("goodbh", mGoodslist.get(pos).getGoodId());
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(CreateOrderHolder createOrderHolder, int pos) {

            }
        });
    }

    private void initView(boolean networkError) {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.mail_order_detail);
        tvCancleOrder = (TextView) findViewById(R.id.tv_delete);
        tvCancleOrder.setOnClickListener(this);
        tvDeleteOrder = (TextView) findViewById(R.id.tv_delete_order);
        tvDeleteOrder.setOnClickListener(this);
        tvRebuy = (TextView) findViewById(R.id.tv_rebuy);
        tvRebuy.setOnClickListener(this);
        tvNowPay = (TextView) findViewById(R.id.tv_now_pay);
        tvNowPay.setOnClickListener(this);
        tvConfirmOrder = (TextView) findViewById(R.id.tv_confirm_order);
        tvConfirmOrder.setOnClickListener(this);
        tvTreasureDetails = (TextView) findViewById(R.id.tv_treasure_details);
        tvTreasureDetails.setOnClickListener(this);
        tv_order_immediate_evaluation = (TextView) findViewById(R.id.tv_order_immediate_evaluation);
        tv_order_immediate_evaluation.setOnClickListener(this);
        LinearLayout networkErrorView = (LinearLayout) findViewById(R.id.ll_network_error);
        TextView tvReload = (TextView) networkErrorView.findViewById(R.id.tv_network_reload);
        tvReload.setOnClickListener(this);
        findViewById(R.id.iv_deal_hash_copy).setOnClickListener(this);
        if (networkError) {
            networkErrorView.setVisibility(View.VISIBLE);
        } else {
            networkErrorView.setVisibility(View.GONE);
            LinearLayout llActualPay = (LinearLayout) findViewById(R.id.ll_actual_pay);
            TextView tvRealTotal = (TextView) findViewById(R.id.tv_order_total);
            TextView tvOrderStatus = (TextView) findViewById(R.id.tv_order_status);
            TextView tvOrderStatusDetail = (TextView) findViewById(R.id.tv_order_status_detail);
            //如果是虚拟商品就隐藏地址
            if(orderType == ORDER_TYPE_VIRTUAL || orderType == ORDER_TYPE_NEW_VIRTUAL){
                rl_address.setVisibility(View.GONE);
            }else {
                rl_address.setVisibility(View.VISIBLE);
            }

            //交易hash
            if(orderDetail.getOrder().getTranHash()!=null&&!orderDetail.getOrder().getTranHash().equals("")){
                ll_deal_hash.setVisibility(View.VISIBLE);
                tv_deal_hash_value.setText(orderDetail.getOrder().getTranHash());
            }else {
                ll_deal_hash.setVisibility(View.GONE);
            }
            //判断商家留言是否显示1
            if(orderDetail.getOrder().getSellerReplay()!=null&&!orderDetail.getOrder().getSellerReplay().equals("")){
                ll_business_message.setVisibility(View.VISIBLE);
                tv_business_message.setText(orderDetail.getOrder().getSellerReplay());
            }else {
                ll_business_message.setVisibility(View.GONE);
            }
            String status = orderDetail.getOrder().getPaymentStatus();
            if (status.equals(OrderAdapter.MALL_NEED_PAY)) {
                tvOrderStatus.setText(R.string.mail_need_pay);
                tvOrderStatusDetail.setText(R.string.mail_submit_and_pay);
                llActualPay.setVisibility(View.GONE);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvNowPay.setVisibility(View.VISIBLE);
                tvCancleOrder.setVisibility(View.VISIBLE);
                tvConfirmOrder.setVisibility(View.GONE);
                tvDeleteOrder.setVisibility(View.GONE);
            } else if (status.equals(OrderAdapter.MALL_NEED_SEND_GOOD)) {
                tvOrderStatus.setText(R.string.mail_need_send_good);
                tvConfirmOrder.setVisibility(View.GONE);
                tvOrderStatusDetail.setText(R.string.mail_send_and_wait);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvNowPay.setVisibility(View.GONE);
                tvCancleOrder.setVisibility(View.GONE);
                tvRebuy.setVisibility(View.VISIBLE);
                tvDeleteOrder.setVisibility(View.GONE);
            } else if (status.equals(OrderAdapter.MALL_NEED_RECEIVE)) {
                tvOrderStatus.setText(R.string.mail_need_receive);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvRebuy.setVisibility(View.VISIBLE);
                tvConfirmOrder.setVisibility(View.VISIBLE);
                tvOrderStatusDetail.setText(R.string.mail_send_and_receive);
                tvDeleteOrder.setVisibility(View.GONE);
            } else if (status.equals(OrderAdapter.MALL_NEED_COMMENT)) {
                tvOrderStatus.setText(R.string.mail_need_assess);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvRebuy.setVisibility(View.VISIBLE);
                tvConfirmOrder.setVisibility(View.GONE);
                tv_order_immediate_evaluation.setVisibility(View.VISIBLE);
                if(orderType == ORDER_TYPE_VIRTUAL|| orderType == ORDER_TYPE_NEW_VIRTUAL){
                    tvOrderStatusDetail.setText(R.string.mail_receive_and_assess_commenting);
                }else {
                    tvOrderStatusDetail.setText(R.string.mail_receive_and_assess);
                }

                tvDeleteOrder.setVisibility(View.GONE);
            } else if (status.equals(OrderAdapter.MALL_ORDER_CLOSE)) {//关闭
                tvOrderStatus.setText(R.string.mail_order_off);
                tvConfirmOrder.setVisibility(View.GONE);
                tvOrderStatusDetail.setText(R.string.mail_order_details_order_close);
                llActualPay.setVisibility(View.GONE);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvNowPay.setVisibility(View.GONE);
                tvCancleOrder.setVisibility(View.GONE);
                tvRebuy.setVisibility(View.VISIBLE);
                tvDeleteOrder.setVisibility(View.VISIBLE);
            } else if (OrderAdapter.MALL_REFUND.equals(status)) {//退款中
                tvOrderStatus.setText(R.string.mail_refund);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvRebuy.setVisibility(View.VISIBLE);
                tvConfirmOrder.setVisibility(View.GONE);
                tvDeleteOrder.setVisibility(View.GONE);
            } else if (OrderAdapter.MALL_COMPLETED.equals(status)) {//已完成
                tvOrderStatus.setText(R.string.mail_done);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvRebuy.setVisibility(View.VISIBLE);
                tvConfirmOrder.setVisibility(View.GONE);
                tvDeleteOrder.setVisibility(View.GONE);
            } else if (OrderAdapter.MALL_CANCEL.equals(status)) {//已取消
                tvOrderStatus.setText(R.string.mail_cancle);
                tvConfirmOrder.setVisibility(View.GONE);
                tvOrderStatusDetail.setText(R.string.mail_order_details_order_cancel);
                llActualPay.setVisibility(View.GONE);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvRebuy.setVisibility(View.VISIBLE);
                tvDeleteOrder.setVisibility(View.VISIBLE);
            } else if (OrderAdapter.MALL_DELETE.equals(status)) {//已删除
                tvOrderStatus.setText(R.string.mail_delete);
                tvConfirmOrder.setVisibility(View.GONE);
                //夺宝支付失败
            } else if (OrderAdapter.SNATCH_PAY_FAIL.equals(status)) {
                tvOrderStatus.setText(R.string.mail_order_snatch_pay_fail);
                tvOrderStatusDetail.setVisibility(View.GONE);
                //夺宝支付成功
            } else if (OrderAdapter.SNATCH_PAY_SUCCESSL.equals(status)) {
                tvOrderStatus.setText(R.string.mail_order_snatch_pay_success);
                tvOrderStatusDetail.setVisibility(View.GONE);
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvTreasureDetails.setVisibility(View.VISIBLE);
                //夺宝已中奖
            } else if (OrderAdapter.SNATCH_WIN.equals(status)) {
                tvOrderStatus.setText(R.string.mail_order_snatch_pay_win);
                tvOrderStatusDetail.setVisibility(View.VISIBLE);
//                tvOrderStatusDetail.setText("恭喜您中奖了！");
//                tvOrderStatusDetail.setTextColor(getColor(R.color.orange_yellow));
                rlBottomOrderStatus.setVisibility(View.VISIBLE);
                tvTreasureDetails.setVisibility(View.VISIBLE);
                //正在支付中
            } else if (OrderAdapter.SNATCH_PAYING.equals(status)) {
                tvOrderStatus.setText(R.string.mail_order_snatch_paying);
                tvOrderStatusDetail.setText("订单正在支付中，请耐心等待");
            }
            //物流信息
            RelativeLayout llShipment = (RelativeLayout) findViewById(R.id.ll_shipment);
            TextView tvShipCompany = (TextView) findViewById(R.id.tv_ship_company);
            TextView tvShipNo = (TextView) findViewById(R.id.tv_ship_no);
            ImageView tvCopyShipNo = (ImageView) findViewById(R.id.iv_copy_ship_no);
            tvCopyShipNo.setOnClickListener(this);
            if (orderDetail.getOrder().getOrderExpressList() != null &&
                    orderDetail.getOrder().getOrderExpressList().size() > 0) {
                llShipment.setVisibility(View.VISIBLE);
                tvShipCompany.setText(orderDetail.getOrder().getOrderExpressList().get(0).getExpressCompany());
                tvShipNo.setText(orderDetail.getOrder().getOrderExpressList().get(0).getTrackingNumber());
            }

            TextView tvStoreName = (TextView) findViewById(R.id.tv_store_name);
            tvStoreName.setText(orderDetail.getOrder().getItems().get(0).getGood().getMallShop().getShopName());
            ImageView ivStoreIcon = (ImageView) findViewById(R.id.iv_order_store);
            LXGlideImageLoader.getInstance().displayRoundCornerImage(this, ivStoreIcon, orderDetail.getOrder()
                    .getItems().get(0).getGood().getMallShop().getShopBrandlog(), R.drawable.shop, R.drawable.shop, 20);

            //虚拟商品没有地址
            if(orderDetail.getOrder().getOrderType() != ORDER_TYPE_VIRTUAL&& orderType!=ORDER_TYPE_NEW_VIRTUAL){
                TextView tvName = (TextView) findViewById(R.id.tv_name);
                tvName.setText(orderDetail.getOrder().getUserAddress().getUserName());
                TextView tvAddress = (TextView) findViewById(R.id.tv_address);
                tvAddress.setText(orderDetail.getOrder().getUserAddress().getArea()
                        + orderDetail.getOrder().getUserAddress().getAddress());
                TextView tvPhone = (TextView) findViewById(R.id.tv_number);
                String phone =orderDetail.getOrder().getUserAddress().getPhone();
                tvPhone.setText(phone.substring(0,3)+"****"+phone.substring(7,phone.length()));
            }

//            tv_order_pre_total.setText("￥" + TCMathUtil.retainAsignDecimalsWithZero(orderDetail.getOrder().get(), 2));
            double afterDiscountTotalPrice = orderDetail.getOrder().getAfterDiscountTotalPrice();
            double totalPrice = orderDetail.getOrder().getTotalPrice();
            TextView tvDueTotal = (TextView) findViewById(R.id.tv_order_due_total);

            List<OrderDetail.OrderBean.ItemsBean> items = orderDetail.getOrder().getItems();
            mGoodslist.clear();
            double tokenPrice = 0;
            for (OrderDetail.OrderBean.ItemsBean item : items) {
                if (item.getGood().getTokenPrices() != null && item.getGood().getTokenPrices().size() > 0) {
                    tokenPricesBean = item.getGood().getTokenPrices().get(0);
                    tokenPrice += (tokenPricesBean.getTokenPayPrice()) * (item.getGoodNum());
                }
                GoodsBean good = item.getGood();
                good.setOrderGoodNum(item.getGoodNum());
                mGoodslist.add(good);
            }

            goodsAdapter.notifyDataSetChanged(mGoodslist);
            if (orderDetail.getOrder().getPaymentDetails() != null &&
                    orderDetail.getOrder().getPaymentDetails().size() > 0) {
                //已付款
                OrderDetail.OrderBean.PaymentDetailBean paymentDetailBean =
                        orderDetail.getOrder().getPaymentDetails().get(0);
                if ("0".equals(paymentDetailBean.getSelectPayType())) {
                    //人民币付款
                    tvRealTotal.setText(ResStringUtil.getString(R.string.common_text_money_unit)+" " + TCMathUtil.retainAsignDecimalsWithZero(afterDiscountTotalPrice, 2));
                    tvDueTotal.setText(ResStringUtil.getString(R.string.common_text_money_unit) + " " + TCMathUtil.retainAsignDecimalsWithZero(totalPrice, 2));
                } else {
                    if(orderDetail.getOrder().getOrderType() == ORDER_TYPE_VIRTUAL||orderType == ORDER_TYPE_NEW_VIRTUAL){
                        tvRealTotal.setText(  paymentDetailBean.getTokenName() + " " +TCMathUtil.retainAsignDecimalsWithZero
                                (paymentDetailBean.getPayTokenAmount(), 2)
                              );
                        tvDueTotal.setText(paymentDetailBean.getTokenName()+ " " +TCMathUtil.retainAsignDecimalsWithZero
                                (totalPrice, 2)
                                );
                    }else {
                        tvRealTotal.setText(TCMathUtil.retainAsignDecimalsWithZero
                                (paymentDetailBean.getPayTokenAmount(), 2) + " " +
                                paymentDetailBean.getTokenName());
                        tvDueTotal.setText(TCMathUtil.retainAsignDecimalsWithZero
                                (TCMathUtil.mul(orderDetail.getOrder().getItems().get(0).getGood().getTokenPrices().get(0).getTokenPayPrice(), orderDetail.getOrder().getItems().get(0).getGoodNum()), 2) + " " +
                                paymentDetailBean.getTokenName());
                    }

                }
            } else {
                tvDueTotal.setText(orderDetail.getOrder().getItems().get(0).getGood().getMallGoodPrice().getPriceUnit()+ " " + TCMathUtil.retainAsignDecimalsWithZero(afterDiscountTotalPrice, 2));
                //待付款
                llActualPay.setVisibility(View.GONE);
            }

            TextView tvOrderBh = (TextView) findViewById(R.id.tv_order_no);
            tvOrderBh.setText(orderDetail.getOrder().getOrderBh());
            TextView tvOrderDate = (TextView) findViewById(R.id.tv_order_time);
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
                    format(new Date(Long.valueOf(orderDetail.getOrder().getPayOrderDate())));
            tvOrderDate.setText(date);
            ImageView tvCopy = (ImageView) findViewById(R.id.iv_copy_order_no);
            tvCopy.setOnClickListener(this);
        }
    }

    private void initData() {
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        HashMap<String, String> map = new HashMap<>();
        map.put("orderBh", orderBh);
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, ORDER_DETAIL_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    orderDetail = gson.fromJson(response, OrderDetail.class);
                    orderType = orderDetail.getOrder().getOrderType();
                    initView(false);
                    if (orderDetail.getOrder().getOrderSaleInfoList() != null) {
                        order_rlv_pre_detail.setVisibility(View.VISIBLE);
                        mlist.clear();
                        mlist.addAll(orderDetail.getOrder().getOrderSaleInfoList());
                        mAdapter.notifyDataSetChanged(mlist);
                    } else {
                        order_rlv_pre_detail.setVisibility(View.GONE);
                    }
                    EventBus.getDefault().post(new UpdateOrderBadgeEvent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                initView(true);
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_delete) {
            DialogUtil.showDialogWithCancle(this, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            cancelOrder(orderBh);
                        }
                    }, getResources().getString(R.string.mail_cancle_buy), getResources().getString(R.string.mall_or_sure_cancle_buy),
                    getResources().getString(R.string.mail_sure), getResources().getString(R.string.cancle));

        } else if (id == R.id.tv_delete_order) {
            DialogUtil.showDialogWithCancle(this, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            deleteOrder(orderBh);
                        }
                    }, getResources().getString(R.string.mail_delete_order), getResources().getString(R.string.mall_delete_order_confirm),
                    getResources().getString(R.string.mail_sure), getResources().getString(R.string.cancle));
        } else if (id == R.id.tv_rebuy) {
            if(orderType== ORDER_TYPE_VIRTUAL||orderType== ORDER_TYPE_NEW_VIRTUAL){
                Intent intent = new Intent(MallOrderDetailActivity.this, ProductDetailsActivity.class);
                intent.putExtra("goodbh",orderDetail.getOrder().getItems().get(0).getGood().getGoodId());
               startActivity(intent);
            }else {
                //todo 商品加入购物车
                LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", EnvironmentVariable.getUserName());
                try {
                    JSONArray jsonArray = new JSONArray();
                    for (OrderDetail.OrderBean.ItemsBean cartItem : orderDetail.getOrder().getItems()) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("goodbh", cartItem.getGood().getGoodId());
                        jsonObject.put("goodNum", cartItem.getGoodNum());
                        jsonObject.put("skuId", cartItem.getGood().getGoodSkus().get(0).getSkuId());
                        jsonArray.put(jsonObject);
                    }
                    map.put("goods", jsonArray.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                MallRequestUtil.getRequest(TAG, CART_ADD_OR_DELETE_URL, map, new MallRequestUtil.MallRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        LoadingDataUtilBlack.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if ("success".equals(jsonObject.optString("result"))) {
                                rebuy();
                                EventBus.getDefault().post(new UpdateCartBadgeEvent());
                            }else if ("fail".equals(jsonObject.optString("result"))){
                                ToastUtil.showToastCenter(jsonObject.optString("msg"));
                            } else {
                                ToastUtil.showToastCenter(getResources().getString(R.string.mail_join_car_fail));
                            }
                        } catch (Exception e) {
                            ToastUtils.showShort(R.string.mail_join_car_fail);
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFail(String error) {
                        LoadingDataUtilBlack.dismiss();
                        ToastUtils.showShort(R.string.mail_join_car_fail);
                    }
                });
            }
        } else if (id == R.id.tv_network_reload) {
            initData();
        } else if (id == R.id.iv_copy_order_no) {
            // 从API11开始android推荐使用android.content.ClipboardManager
            // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(orderDetail.getOrder().getOrderBh());
            ToastUtil.showToast(this,R.string.mail_order_copy_success);
        } else if (id == R.id.iv_copy_ship_no) {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(orderDetail.getOrder().getOrderExpressList().get(0).getTrackingNumber());
            ToastUtil.showToast(this, R.string.mall_copy_ship_no_success);
        }else if(id == R.id.tv_now_pay){
                //立即付款
            ArrayList<String> orderIds = new ArrayList<>();
            orderIds.add(orderDetail.getOrder().getOrderBh());
            if (orderDetail.getOrder().getOrderType()== ORDER_TYPE_TREASURE) {
                //夺宝支付页面跳转
                MallSelectionPayNoAliWxActivity.start(this,orderIds , orderDetail.getOrder()
                                .getItems().get(0).getGood().getGoodId()
                        , orderDetail.getOrder().getTotalPrice()+ "");
            } else if(orderDetail.getOrder().getOrderType()== ORDER_TYPE_VIRTUAL){
                //虚拟商品支付页面跳转
                MallVirtualProductSelectionPayActivity.start(this,orderIds , orderDetail.getOrder().getItems().get(0).getGood().getGoodName(),orderDetail.getOrder().getTotalPrice()+ ""
                         );
            }else{
                //普通商品跳支付
                Intent intent = new Intent(this, SelectionPayActivity.class);
                intent.putStringArrayListExtra("orderId", orderIds);
                intent.putExtra("orderAmount", orderDetail.getOrder().getTotalPrice()+ "");
                intent.putExtra("orderTitle", orderDetail.getOrder().getItems().get(0).getGood().getGoodName());
                startActivity(intent);
            }
        }else if(id == R.id.tv_treasure_details){
            //跳转夺宝详情页面
            MallWinTreasureDetailsActivity.start(this, orderDetail.getOrder().getItems()
                    .get(0).getGood().getGoodId(),orderDetail.getOrder().getOrderType()+"");
        } else if (id == R.id.tv_confirm_order) {
            //确认收货
            DialogUtil.showDialogWithCancle(this, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            goToConfirmOrder(orderBh);
                        }
                    },getResources().getString(R.string.common_text_hint),getResources().getString(R.string.mall_confirm_order),
                    getResources().getString(R.string.mail_sure),getResources().getString(R.string.cancle));
        }else if(id == R.id.iv_deal_hash_copy){
            //复制交易哈希
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(orderDetail.getOrder().getTranHash());
            ToastUtil.showToast(this, R.string.mall_copy_ship_success);
        }else if(id == R.id.tv_order_immediate_evaluation){
            //立即评价
            Intent intent = new Intent(this, ToEvaluateActivity.class);
            intent.putExtra("orderBh",orderBh);
            startActivity(intent);
        }
    }

    private void rebuy() {
        View contentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        contentView = inflater.inflate(R.layout.layout_rebuy_pop, null);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        final PopupWindow abortAlert = new PopupWindow(contentView,
                screenWidth / 6 * 5, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        TextView tvAbort = (TextView) contentView.findViewById(R.id.tv_abort_checkout);
        TextView tvResume = (TextView) contentView.findViewById(R.id.tv_resume_checkout);
        tvAbort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                abortAlert.dismiss();
            }
        });
        tvResume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                abortAlert.dismiss();
                //跳转购物车
                try {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.fragment.MallCartFragment"), bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
        abortAlert.setContentView(contentView);
        abortAlert.setFocusable(true);
        abortAlert.setBackgroundDrawable(new BitmapDrawable());
        abortAlert.setOutsideTouchable(false);
        abortAlert.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 取消订单
     * @param orderBh
     */
    private void cancelOrder(String orderBh){
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        JSONArray jsonArray = new JSONArray();
        try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orderbh", orderBh);
                jsonObject.put("status", "cannelOrder");
                jsonArray.put(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orders", jsonArray.toString());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.CHANGE_ORDER_STATUS_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if("success".equals(jsonObject.getString("result"))){
                        finish();
                    }else {
                        ToastUtil.showToastCenter(getResources().getString(R.string.mall_cancle_fail));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_cancle_fail));
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToastCenter(getResources().getString(R.string.mall_cancle_fail));
            }
        });
    }

    /**
     * 删除订单
     * @param orderBh
     */
    private void deleteOrder(String orderBh){
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        JSONArray jsonArray = new JSONArray();
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderbh", orderBh);
            jsonObject.put("status", "deleteOrder");
            jsonArray.put(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orders", jsonArray.toString());
        MallRequestUtil.getRequest(TAG, MallRequestUtil.CHANGE_ORDER_STATUS_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if("success".equals(jsonObject.getString("result"))){
                        finish();
                    }else {
                        ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_fail));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_fail));
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_fail));
            }
        });
    }

    //确认收货
    private void goToConfirmOrder(String orderBh) {
        LoadingDataUtilBlack.show(this, getString(R.string.common_text_please_wait));
        try {
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderbh", orderBh);
            jsonObject.put("status", "enterReceived");
            jsonArray.put(jsonObject);
            HashMap<String, String> map = new HashMap<>();
            map.put("userId", EnvironmentVariable.getUserName());
            map.put("orders", jsonArray.toString());
            MallRequestUtil.getRequest(TAG, MallRequestUtil.CHANGE_ORDER_STATUS_URL, map, new MallRequestUtil.MallRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    LoadingDataUtilBlack.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if ("success".equals(jsonObject.getString("result"))) {
                            ToastUtils.showShort(R.string.mall_confirm_order_success);
                            finish();
                        } else {
                            ToastUtil.showToastCenter(getResources().getString(R.string.mall_confirm_order_fail));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        ToastUtil.showToastCenter(getResources().getString(R.string.mall_confirm_order_fail));
                    }
                }

                @Override
                public void onFail(String error) {
                    LoadingDataUtilBlack.dismiss();
                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_confirm_order_fail));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            LoadingDataUtilBlack.dismiss();
            ToastUtil.showToastCenter(getResources().getString(R.string.mall_confirm_order_fail));
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
}
